import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

import { getItem } from '@/utils/storage'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('@/views/main/main.vue'),
    children: [
      {
        path: '/admin-user',
        name: 'admin-user',
        component: () => import('@/views/main/leader/admin-user.vue')
      },
      {
        path: '/common-user',
        name: 'common-user',
        component: () => import('@/views/main/leader/common-user.vue')
      }
    ]
  }
]

const router = createRouter({
  routes,
  history: createWebHashHistory()
})

router.beforeEach((to) => {
  if (to.path !== '/login') {
    const token = getItem('token')
    if (!token) {
      return '/login'
    }
  }
  // 重定向main
  if (to.path === '/main') {
    const userInfo = getItem('user_info')
    if (userInfo.dataScope === -1) {
      return '/admin-user'
    } else {
      return '/common-user'
    }
  }
})

export default router
